<template>
  <div class="checkout">
    <div class="header">
      <div class="content">确认订单</div>
    </div>

    <div class="container">
      <!-- 收货地址 -->
      <div class="address-section">
        <div class="section-title">收货地址</div>
        <div class="address-list" v-if="addressList.length > 0">
          <div v-for="addr in addressList"
               :key="addr.id"
               class="address-item"
               :class="{ active: selectedAddressId === addr.id }"
               @click="selectAddress(addr)">
            <div class="info">
              <p class="name">{{ addr.realName }}</p>
              <p class="phone">{{ addr.tel }}</p>
              <p class="detail">{{ addr.regionId }}{{ addr.cityId }}{{ addr.address }}</p>
              <el-tag size="small" type="warning" v-if="addr.isDefault">默认</el-tag>
            </div>
            <div class="actions">
              <el-button type="text" @click.stop="editAddress(addr)">编辑</el-button>
              <el-button type="text" @click.stop="deleteAddress(addr.id)">删除</el-button>
            </div>
          </div>
          <div class="address-item add" @click="openAddressDialog()">
            <el-icon><Plus /></el-icon>
            <span>新增收货地址</span>
          </div>
        </div>
        <div v-else class="empty-address">
          <el-empty description="暂无收货地址">
            <el-button type="primary" @click="openAddressDialog">添加收货地址</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="order-section">
        <div class="section-title">商品信息</div>
        <div class="product-list">
          <div class="product-header">
            <span class="col product">商品信息</span>
            <span class="col">单价</span>
            <span class="col">数量</span>
            <span class="col">小计</span>
          </div>
          <div v-for="item in orderItems" :key="item.id" class="product-item">
            <div class="col product">
              <img :src="item.image" :alt="item.title">
              <div class="info">
                <div class="title">{{ item.title }}</div>
                <div class="spec">{{ item.specs }}</div>
              </div>
            </div>
            <div class="col price">¥{{ formatPrice(item.price) }}</div>
            <div class="col quantity">{{ item.quantity }}</div>
            <div class="col subtotal">¥{{ formatPrice(item.price * item.quantity) }}</div>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-section">
        <div class="section-title">支付方式</div>
        <div class="payment-options">
          <el-radio-group v-model="paymentType">
            <el-radio :label="1">全额支付</el-radio>
            <el-radio :label="2">分期付款</el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 订单备注 -->
      <div class="remark-section">
        <div class="section-title">订单备注</div>
        <el-input
          v-model="buyerMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入订单备注（选填）"
          maxlength="200"
          show-word-limit
        />
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="submit-bar">
      <div class="content">
        <div class="total">
          <span>总计：</span>
          <span class="price">¥{{ formatPrice(totalAmount) }}</span>
          <span class="count">(共{{ totalQuantity }}件)</span>
        </div>
        <div class="buttons">
          <el-button @click="$router.back()">返回购物车</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">
            提交订单
          </el-button>
        </div>
      </div>
    </div>

    <!-- 地址编辑弹窗 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="isEditingAddress ? '修改地址' : '新增地址'"
      width="500px"
      @close="resetAddressForm"
    >
      <el-form :model="addressForm" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="addressForm.userName" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="addressForm.tel" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="订单地址">
          <el-select v-model="addressForm.regionId" placeholder="选择省会/直辖市" size="large" style="width: 150px" @change="regionsChange">
            <el-option v-for="region in options"
                       :key="region.cityname"
                       :label="region.cityname"
                       :value="region.id"></el-option>
          </el-select>
          <el-select v-model="addressForm.cityId" size="large" style="width: 150px" placeholder="选择城市" filterable>
            <el-option v-for="city in cityOptions"
                       :key="city.cityname"
                       :label="city.cityname"
                       :value="city.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="addressForm.address" placeholder="详细地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="savingAddress">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 状态管理
const addressList = ref([])
const selectedAddressId = ref(null)
const selectedUserName = ref('')
const addressDialogVisible = ref(false)
const isEditingAddress = ref(false)
const submitting = ref(false)
const savingAddress = ref(false)
const paymentType = ref(1)
const buyerMessage = ref('')
const orderItems = ref([])
const options = ref([])
const cityOptions = ref([])

// 地址表单
const addressForm = ref({
  realName: '',
  userName: '',
  tel: '',
  regionId: '',
  cityId: '',
  address: '',
  isDefault: false,
  id: ''
})

// 计算属性
const totalAmount = computed(() => {
  const total = orderItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  return Number(total.toFixed(2)) // 返回数值而不是字符串
})
const totalQuantity = computed(() => {
  return orderItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 地区选择变化处理
const regionsChange = (value) => {
  axios.get('/logic/tools/select/regions/' + value).then(res => {
    cityOptions.value = res.data.data
  })
}

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await axios.get(`/logic/sysuser/addresses/${addressForm.value.userName}`)
    addressList.value = response.data
    // 如果有地址，默认选中第一个地址
    if (addressList.value.length > 0) {
      const defaultAddress = addressList.value[0]
      selectedAddressId.value = defaultAddress.id
      selectedUserName.value = defaultAddress.userName
    }
  } catch (error) {
    console.error('获取地址列表错误:', error)
    ElMessage.error('获取地址列表失败')
    addressList.value = []
  }
}

// 选择地址
const selectAddress = (address) => {
  selectedAddressId.value = address.id
  selectedUserName.value = address.userName
}

// 打开地址弹窗
const openAddressDialog = (address = null) => {
  axios.get('logic/tools/select/regions/1').then(res => {
    options.value = res.data.data
  })
  isEditingAddress.value = !!address
  if (address) {
    addressForm.value = { ...address }
  } else {
    resetAddressForm()
  }
  addressDialogVisible.value = true
}

// 重置地址表单
const resetAddressForm = () => {
  addressForm.value = {
    userName: '',
    tel: '',
    regionId: '',
    cityId: '',
    address: '',
    isDefault: false,
    id: ''
  }
}

// 编辑地址
const editAddress = (address) => {
  openAddressDialog(address)
}

// 删除地址
const deleteAddress = async (id) => {
  try {
    await axios.delete(`/api/address/${id}`)
    ElMessage.success('地址删除成功')
    await fetchAddressList()
  } catch (error) {
    ElMessage.error('删除地址失败')
  }
}

// 保存地址
const saveAddress = async () => {
  // 验证必填字段
  if (!addressForm.value.userName || !addressForm.value.tel ||
    !addressForm.value.regionId || !addressForm.value.cityId ||
    !addressForm.value.address) {
    ElMessage.warning('请填写完整的地址信息')
    return
  }

  savingAddress.value = true
  try {
    const params = new URLSearchParams()
    params.append('userName', addressForm.value.userName)
    params.append('regionId', addressForm.value.regionId)
    params.append('cityId', addressForm.value.cityId)
    params.append('address', addressForm.value.address)
    params.append('tel', addressForm.value.tel)
    params.append('realName', addressForm.value.userName)

    const response = await axios.post('/logic/sysuser/addAddress', params)

    if (response.data.code === 200) {
      ElMessage.success('保存地址成功')
      addressDialogVisible.value = false
      await fetchAddressList()
    } else {
      throw new Error(response.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存地址错误:', error)
    ElMessage.error(error.message || '保存地址失败')
  } finally {
    savingAddress.value = false
  }
}

// 初始化订单数据
const initOrderData = () => {
  const orderItemsStr = route.query.orderItems
  if (orderItemsStr) {
    try {
      orderItems.value = JSON.parse(decodeURIComponent(orderItemsStr))
    } catch (error) {
      ElMessage.error('订单数据解析失败')
      router.push('/')
    }
  }
}

// 提交订单
// 提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  submitting.value = true
  try {
    // 构建订单项数据
    const items = orderItems.value.map(item => ({
      itemId: item.itemId,
      itemTitle: item.itemTitle,
      quantity: item.quantity,
      price: Number(item.price), // 确保价格是数值类型
      totalFee: Number((item.price * item.quantity).toFixed(2)), // 确保总价是数值类型
      picPath: item.image,
      status: item.status
    }))

    // 使用正确的请求格式和数据类型
    const response = await axios({
      method: 'post',
      url: '/orders/create',
      headers: {
        'Content-Type': 'application/json'
      },
      data: items, // 订单项数据放在请求体中
      params: { // 其他参数放在URL参数中，注意数据类型
        userName: selectedUserName.value,
        payment: totalAmount.value, // 已经是数值类型了
        paymentType: Number(paymentType.value),
        postFee: '0',
        buyerMessage: buyerMessage.value,
        addressId: Number(selectedAddressId.value)
      }
    })

    if (response.data && response.data.orderId) {
      ElMessage.success('订单创建成功')
      // router.push(`/payment/${response.data.orderId}`)
    } else {
      throw new Error('订单创建失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error(error.message || '提交订单失败')
  } finally {
    submitting.value = false
  }
}

// 生命周期钩子
onMounted(async () => {
  initOrderData()
  try {
    const response = await axios.get('/logic/sysuser/current')
    addressForm.value.userName = response.data.data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
  fetchAddressList()
})
</script>

<style scoped>
.checkout {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.header .content {
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
  line-height: 60px;
  font-size: 18px;
  font-weight: bold;
  padding: 0 20px;
}

.container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.address-section,
.order-section,
.payment-section,
.remark-section {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.address-item {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 15px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409EFF;
}

.address-item.active {
  border-color: #409EFF;
  background-color: #f6f9ff;
}

.address-item.add {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  border-style: dashed;
}

.address-item.add .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.address-item.add:hover {
  color: #409EFF;
}

.address-item .info .name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.address-item .info .phone {
  color: #666;
  margin-bottom: 8px;
}

.address-item .info .detail {
  color: #666;
  line-height: 1.5;
}

.address-item .actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.product-list .product-header {
  display: grid;
  grid-template-columns: 3fr 1fr 1fr 1fr;
  padding: 15px 0;
  background: #f8f8f8;
  text-align: center;
}

.product-list .product-header .col.product {
  text-align: left;
  padding-left: 20px;
}

.product-item {
  display: grid;
  grid-template-columns: 3fr 1fr 1fr 1fr;
  padding: 20px 0;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.product-item .col {
  text-align: center;
}

.product-item .col.product {
  display: flex;
  align-items: center;
  text-align: left;
  padding-left: 20px;
}

.product-item .col.product img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-item .col.product .info .title {
  margin-bottom: 8px;
}

.product-item .col.product .info .spec {
  color: #999;
  font-size: 12px;
}

.product-item .col.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.payment-options {
  padding: 20px 0;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.submit-bar .content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.submit-bar .total {
  margin-right: 20px;
}

.submit-bar .total .price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 0 5px;
}

.submit-bar .total .count {
  color: #999;
}

.submit-bar .buttons {
  display: flex;
  gap: 10px;
}

.region-select {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

/* 编辑地址弹窗样式 */
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

/* 空状态样式 */
.empty-address {
  padding: 40px 0;
  text-align: center;
}

/* Element Plus 相关样式调整 */
:deep(.el-dialog__body) {
  padding-top: 20px;
}

:deep(.el-input__inner) {
  width: 100%;
}

:deep(.el-radio) {
  margin-right: 20px;
}

:deep(.el-button--text) {
  padding: 0 10px;
}
</style>
